#include "HairColorPanelWidget.h"
#include <QPainter>
#include <QTimer>

HairColorPanelWidget::HairColorPanelWidget(QWidget* parent)
	:HairColorPanelWidget("0", parent)
{

}

HairColorPanelWidget::HairColorPanelWidget(const QString& id, QWidget* parent)
	: QWidget(parent)
	, ui(new Ui::HairColorPanelWidgetClass())
	, m_id(id)
{
	ui->setupUi(this);
	setFixedHeight(80);
	hide();
	createLayout();
}

HairColorPanelWidget::~HairColorPanelWidget()
{
	delete ui;
}

void HairColorPanelWidget::setHairStyleId(const QString& hairStyleId)
{
	m_hairId = hairStyleId;
}

void HairColorPanelWidget::createLayout()
{
	m_layout = new QGridLayout(this);
	m_layout->setSpacing(0);
	m_layout->setContentsMargins(0, 0, 0, 0);

	for (int i(0); i < 9; ++i) {
		HairColorItemWidget* hairColorItem = new HairColorItemWidget(QString::number(i));
		connect(hairColorItem, &HairColorItemWidget::sigColorSelected, this, &HairColorPanelWidget::onColorSelected);
		m_hairColorMap[QString::number(i)] = hairColorItem;
		int row = i / 5;
		int col = i % 5;
		m_layout->addWidget(hairColorItem, row, col);
	}
}

void HairColorPanelWidget::onColorSelected(const QString& id)
{
	for (HairColorItemWidget* item : m_hairColorMap.values()) {
		if (item->getId() == id) {
			item->setSelected(true);
		}
		else {
			item->setSelected(false);
		}
	}
}

void HairColorPanelWidget::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	painter.setRenderHints(QPainter::SmoothPixmapTransform | QPainter::Antialiasing);
	painter.setPen(Qt::NoPen);
	painter.setBrush(QColor(49, 49, 49));
	painter.drawRoundedRect(rect(), 6, 6);


	painter.setPen(Qt::red);
	painter.drawText(rect().center(), m_id);
}

void HairColorPanelWidget::showEvent(QShowEvent* event)
{
	QWidget::showEvent(event);
	//QTimer::singleShot(0, [=] {
	//	// 左右margin和4个间隔
	//	const int perWidth = (width() - 10 - 4 * 5 - 1) / 5;
	//	// 按照每行5个元素排列
	//	for (HairColorItemWidget* hairColorItem : m_hairColorMap.values()) {
	//		hairColorItem->setFixedSize(perWidth, perWidth);
	//	}
	//	// 设置高度

	//	int cols = qCeil((qreal)m_hairColorMap.size() / 5);

	//	setFixedHeight(cols * perWidth + 10 + 6);
	//	});
}
